package com.yuerlive.rainbow.module.login;

import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yuerlive.rainbow.API;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.common.Constants;
import com.yuerlive.rainbow.common.SimpleTextWatcher;
import com.yuerlive.rainbow.entity.BaseData;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.module.login.presenter.LoginContract;
import com.yuerlive.rainbow.module.login.presenter.LoginPresenter;
import com.yuerlive.rainbow.module.main.MainActivity;
import com.yuerlive.rainbow.observer.Observerable;
import com.yuerlive.rainbow.observer.ObserverableType;
import com.yuerlive.rainbow.utils.GlideUtil;
import com.yuerlive.rainbow.utils.PreferenceUtils;
import com.yuerlive.rainbow.utils.ThirdLoginUtils;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.widget.CustomDialog;

import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Admin on 2017/5/21.
 */

public class LoginActivity extends BaseActivity implements LoginContract.View, ThirdLoginUtils.UserLoginInfoListenter {
    @BindView(R.id.llParent)
    LinearLayout llParent;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.etLogintMobile)
    EditText etLogintMobile;
    @BindView(R.id.etLogintVerification)
    EditText etLogintVerification;
    @BindView(R.id.tvGetVerification)
    TextView tvGetVerification;
    @BindView(R.id.tvCompeleted)
    TextView tvCompeleted;
    @BindView(R.id.tvProtocol)
    TextView tvProtocol;
    private CustomDialog dialog;
    @BindView(R.id.ivClear)
    ImageView ivClear;
    private String imgCode;
    LoginContract.Presenter presenter;

    private int SMS_COUNTDOWN = 60;

    private int countDown = SMS_COUNTDOWN;

    private InnerHandler mHandler;
    private static final int CODE_SMS_COUNTDOWN = 0X1001;
    private static final String LOGIN_FLAG = "login";
    private static final int REQUECT_CODE_READ_PHONE_STATE = 2;
    private boolean isMobileFormateSure;
    private boolean isVerificationFormatSure;
    private ImageView ivVerificationPic;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews() {
        setTitle("");

        presenter = new LoginPresenter(this);
        mHandler = new InnerHandler(this);
        setListener();
        ThirdLoginUtils.getInstance().setListener(this);
    }

    private void setListener() {
        etLogintMobile.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                if (etLogintMobile.getText().toString().length() >= 11 && checkoutPhone(etLogintMobile.getText().toString())) {
                    tvGetVerification.setTextColor(mActivity.getResources().getColor(R.color.input_red));
                    isMobileFormateSure = true;
                } else {
                    tvGetVerification.setTextColor(mActivity.getResources().getColor(R.color.input_red_60));
                    isMobileFormateSure = false;
                }
                if (s.length() > 1) {
                    ivClear.setVisibility(View.VISIBLE);
                } else {
                    ivClear.setVisibility(View.GONE);
                }
                if (etLogintMobile.getText().toString().length() > 0) {
                    ivClear.setVisibility(View.VISIBLE);
                } else {
                    ivClear.setVisibility(View.GONE);
                }
            }
        });
    }

    @OnClick({R.id.tvGetVerification, R.id.tvCompeleted, R.id.ivQQ, R.id.ivWeixin, R.id.tvProtocol, R.id.ivClear})
    public void onClick(View view) {
        //网络请求要获取设置id  要请求此权限
        requestPermission(new String[]{Manifest.permission.READ_PHONE_STATE}, 0x0003);
        switch (view.getId()) {
            case R.id.tvGetVerification:
                if (checkoutPhone(etLogintMobile.getText().toString())) {
                    showInputVerificationDialog();
                } else {
                    // showToast("请输入正确的手机号码");
                    showSnackbar(llParent, "请输入正确的手机号码", 0);
                }
                break;
            case R.id.tvCompeleted:
                if (isMobileFormateSure && isVerificationFormatSure) {
                    presenter.login(etLogintMobile.getText().toString(), etLogintVerification.getText().toString());
                } else {
                    if (!isMobileFormateSure) {
                        showSnackbar(llParent, "请输入正确的手机号码", 1);
                        return;
                    }
                    if (!isVerificationFormatSure) {
                        showSnackbar(llParent, "请输入正确的验证码", 0);
                        return;
                    }
                }
                break;
            case R.id.ivQQ:
                ThirdLoginUtils.getInstance().ThridLogin( SHARE_MEDIA.QQ);
                break;
            case R.id.ivWeixin:
                ThirdLoginUtils.getInstance().ThridLogin( SHARE_MEDIA.WEIXIN);
                break;
            case R.id.tvProtocol:
                break;
            case R.id.ivClear:
                etLogintMobile.getText().clear();
                break;

        }
    }

    private boolean checkoutPhone(String phoneNum) {
        return phoneNum.matches(Constants.PHONE_FORMAT);
    }

    /**
     *
     *
     */
    private void showInputVerificationDialog() {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.dialog_edit_verification, null);
        dialog = new CustomDialog(mActivity, contentView) {
            @Override
            public void dismiss() {
                super.dismiss();
                imgCode = "";
            }
        };
        RelativeLayout rlInput = (RelativeLayout) contentView.findViewById(R.id.rlInput);
        TextView tvTitle = (TextView) contentView.findViewById(R.id.tvTitle);
        final ImageView ivClear = (ImageView) contentView.findViewById(R.id.ivClear);
        final EditText etInput = (EditText) contentView.findViewById(R.id.etInput);
        TextView tvCancle = (TextView) contentView.findViewById(R.id.tvCancle);
        TextView tvSure = (TextView) contentView.findViewById(R.id.tvSure);
        ImageView ivDelete = (ImageView) contentView.findViewById(R.id.ivDelete);
        ivDelete.setOnClickListener((v) -> dialog.dismiss());
        ivVerificationPic = (ImageView) contentView.findViewById(R.id.ivVerificationPic);
        GlideUtil.loadNoCache(mActivity, API.CHECK_CODE + etLogintMobile.getText().toString(), ivVerificationPic);
        ivClear.setVisibility(View.GONE);
        tvTitle.setText(getResources().getString(R.string.please_input_pic_content));
        ivClear.setVisibility(View.GONE);
        popupInputMethodWindow();
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (checkoutInputCode(etInput)) {
                    isVerificationFormatSure = true;
                } else {
                    isVerificationFormatSure = false;
                }
                if (s.length() > 0) {
                    ivClear.setVisibility(View.VISIBLE);
                } else {
                    ivClear.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etInput.setText("");
                imgCode = "";
            }
        });
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!checkoutInputCode(etInput)) {
                    showSnackbar(llParent, "验证码不正确，请确认后重试", 0);
                    return;
                }
                imgCode = etInput.getText().toString();
                imgCode = "";
                presenter.getSmsCode(etLogintMobile.getText().toString(), etInput.getText().toString(),1);
            }
        });

    }

    private boolean checkoutInputCode(EditText etInput) {
        return etInput.getText().toString().trim().length() == 4;
    }

    private void popupInputMethodWindow() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) LoginActivity.this.getSystemService(Service.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 0);
    }

    @Override
    public void setPresenter(LoginContract.Presenter presenter) {
        super.presenter = presenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showImgCode(String imgUrl) {

    }

    @Override
    public void loginResult(User user) {
        if (user == null) {
            showSnackbar(llParent, "登录失败", 0);
        } else {
            showSnackbar(llParent, "登录成功", 0);
            UserProxy.setUser(user);
            initDaily();
            //NimHelper.login(NimHelper.generateLoginInfo(user.getUserId(), user.getUserId()));
            //第一次跳转CompleteInfoActivity   以后都跳转到MainActivity
            String vacationer = PreferenceUtils.getString(LOGIN_FLAG);
            if (user.getFirstLogin() == 0) {
                jumpToActivity(MainActivity.class);
            } else {
                jumpToActivity(CompleteInfoActivity.class);
            }
            Observerable.getInstance().notifyChange(ObserverableType.LOGIN, null);
            finish();
        }
    }

    @Override
    public void sendSuccess(BaseData baseData) {
        switch (baseData.getCode()) {
            case 0:
                showSnackbar(llParent, "发送成功", 0);
                mHandler.sendEmptyMessage(CODE_SMS_COUNTDOWN);
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                break;
            default:
                showSnackbar(llParent, baseData.getResult(), 0);
                resetVerification();
        }
    }

    @Override
    public void bindMobileSuccess(BaseData baseData) {

    }

    @Override
    public void showFail(String message, String api) {
        showSnackbar(llParent, message, 0);
        switch (api) {
            case API.SEND_SMS_CODE:
                resetVerification();
                break;
        }
    }

    @Override
    public void loginFaild(int code, String result) {
        showSnackbar(getRootView(mActivity),result,0);
    }

    private void resetVerification() {
        if (ivVerificationPic != null) {
            GlideUtil.loadNoCache(mActivity, API.CHECK_CODE + etLogintMobile.getText().toString(), ivVerificationPic);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private static class InnerHandler extends Handler {
        WeakReference<LoginActivity> weakReference;
        LoginActivity activity;

        public InnerHandler(LoginActivity activity) {
            weakReference = new WeakReference<LoginActivity>(activity);
            this.activity = weakReference.get();
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_SMS_COUNTDOWN:
                    if (activity.countDown-- > 0) {
                        activity.tvGetVerification.setText("重新获取(" + activity.countDown + ")");
                        activity.tvGetVerification.setEnabled(false);
                        sendEmptyMessageDelayed(CODE_SMS_COUNTDOWN, 1000);
                        activity.tvGetVerification.setTextColor(activity.getResources().getColor(R.color.input_red_60));
                    } else {
                        activity.tvGetVerification.setEnabled(true);
                        activity.countDown = activity.SMS_COUNTDOWN;
                        activity.tvGetVerification.setText("重新获取");
                        activity.tvGetVerification.setTextColor(activity.getResources().getColor(R.color.input_red));
                    }
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ThirdLoginUtils.getInstance().removeListener();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void setLoginInfo(Map<String, String> data, SHARE_MEDIA platform) {
        String icon = data.get("iconurl");
        String nickname = data.get("name");
        String sex = data.get("gender");
        if ("男".equals(sex)) {
            sex = String.valueOf(0);
        } else {
            sex = String.valueOf(1);
        }
        String uid = data.get("uid");
        String openId = data.get("openid");
        String platform2 = platform == SHARE_MEDIA.QQ ? String.valueOf(1) : String.valueOf(2);
        presenter.thirdLogin(icon, nickname, openId, platform2, sex, String.valueOf(1));
    }

    @Override
    public void hideProgressBar() {

    }

    private void initDaily(){
        long current = System.currentTimeMillis();
        String prefix = UserProxy.getUser().getUserId();
        if (PreferenceUtils.getLong(prefix + "_START_TIME") <= 0) {
            PreferenceUtils.putLong(prefix + "_START_TIME", current);
        } else {
            Date date = new Date(PreferenceUtils.getLong(prefix + "_START_TIME"));
            Date currentDate = new Date(current);
            if (date.getDate() == currentDate.getDate() && date.getMonth() == currentDate.getMonth()) { //同一天
                //PreferenceUtils.putLong("START_TIME", current);
            } else {
                PreferenceUtils.putLong(prefix + "_START_TIME", current);  //新的一天
            }
        }
    }
}
